package com.zhuzi.guicollect.controller.fx;

import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXComboBox;
import com.jfoenix.controls.JFXTextField;
import com.jfoenix.validation.RequiredFieldValidator;
import com.zhuzi.guicollect.utils.AlertUtils;
import com.zhuzi.guicollect.utils.IniUtils;
import com.zhuzi.guicollect.utils.SysUtils;
import de.felixroske.jfxsupport.FXMLController;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.SingleSelectionModel;
import javafx.util.StringConverter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.kordamp.ikonli.fontawesome5.FontAwesomeSolid;
import org.kordamp.ikonli.javafx.FontIcon;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.util.ResourceBundle;

/**
 * @Author: MI
 * @Date: 2022/1/16/16:55
 * @Description:
 */
@Slf4j
@FXMLController
public class WxController implements Initializable {
    private static final String ERROR = "error";

    @FXML
    public JFXComboBox<Label> jfxEditableComboBox;

    @FXML
    public JFXTextField textDir;
    @FXML
    public JFXTextField textUrl;
    public JFXButton cjBut;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        //采集用户输入框校验
        RequiredFieldValidator validator = new RequiredFieldValidator();
        validator.setMessage("请输入");
        FontIcon warnIcon = new FontIcon(FontAwesomeSolid.EXCLAMATION_TRIANGLE);
        warnIcon.getStyleClass().add("info");
        validator.setIcon(warnIcon);
        textUrl.getValidators().add(validator);
        textUrl.focusedProperty().addListener((o, oldVal, newVal) -> {
            if (!newVal) {
                textUrl.validate();
            }
        });

        //
        validator = new RequiredFieldValidator();
        validator.setMessage("存放路径不能为空");
        warnIcon = new FontIcon(FontAwesomeSolid.EXCLAMATION_TRIANGLE);
        warnIcon.getStyleClass().add(ERROR);
        validator.setIcon(warnIcon);
        textDir.getValidators().add(validator);
        textDir.focusedProperty().addListener((o, oldVal, newVal) -> {
            if (!newVal) {
                textDir.validate();
            }
        });


        //下拉框
        ChangeListener<? super Boolean> comboBoxFocus = (o, oldVal, newVal) -> {
            if (!newVal) {
                jfxEditableComboBox.validate();
            }
        };
        jfxEditableComboBox.focusedProperty().addListener(comboBoxFocus);
        jfxEditableComboBox.getEditor().focusedProperty().addListener(comboBoxFocus);
        jfxEditableComboBox.setConverter(new StringConverter<Label>() {
            @Override
            public String toString(Label object) {
                return object == null ? "" : object.getText();
            }

            @Override
            public Label fromString(String string) {
                return string == null || string.isEmpty() ? null : new Label(string);
            }
        });

        //textDir 设置值
        String hisDir = IniUtils.read("default", "dir");
        if (!StringUtils.equals("d:/pic", hisDir) & SysUtils.isDirExit(hisDir)) {
            if (StringUtils.contains(hisDir, "A-jsl")) {
                String[] split = hisDir.split("A-jsl");
                hisDir = split[0] + "D-微信公众号";
            }
            String finalHisDir = hisDir;
            Platform.runLater(() -> {
                textDir.setText(finalHisDir);
            });
        }
        cjBut.getStyleClass().add("btn-info");
    }

    /*public void selectItem(MouseEvent mouseEvent) {
        ChangeListener<? super Boolean> comboBoxFocus = (o, oldVal, newVal) -> {
            if (!newVal) {
                jfxEditableComboBox.validate();
            }
        };
        jfxEditableComboBox.focusedProperty().addListener(comboBoxFocus);
        jfxEditableComboBox.getEditor().focusedProperty().addListener(comboBoxFocus);
        jfxEditableComboBox.setConverter(new StringConverter<Label>() {
            @Override
            public String toString(Label object) {
                return object == null ? "" : object.getText();
            }

            @Override
            public Label fromString(String string) {
                return string == null || string.isEmpty() ? null : new Label(string);
            }
        });
    }*/


    /**
     * 获取选择
     *
     * @param actionEvent
     */
    public void butGetSel(ActionEvent actionEvent) throws IOException {
        if (!textDir.validate()
                || !textUrl.validate()
                || !jfxEditableComboBox.validate()) {
            AlertUtils.showNotifications("提示", "请输入", 3, Pos.CENTER_RIGHT);
            return;
        }
        if (jfxEditableComboBox.validate()) {
            SingleSelectionModel<Label> selectionModel = jfxEditableComboBox.getSelectionModel();
            Label selectedItem = selectionModel.getSelectedItem();
            String text = selectedItem.getText();

            //保存路劲
            String path = Paths.get(textDir.getText(), text).toString();
            cjBut.setDisable(true);
            try {
                String title = cal(path);
                AlertUtils.showNotifications("提示", title + " 采集完成", 3, Pos.BOTTOM_RIGHT);
            } catch (Exception e) {
                log.error("采集公众号异常", e);
                AlertUtils.showNotifications("提示", "输入错误信息" + e.getLocalizedMessage(), 3, Pos.BOTTOM_RIGHT);
            }
            Platform.runLater(() -> {
                cjBut.setDisable(false);
            });
        }
    }

    /**
     * 抓取微信公众号
     *
     * @param path 保存路劲
     * @return 返回采集的标题
     */
    private String cal(String path) throws Exception {
        Connection.Response response = Jsoup.connect(textUrl.getText()).method(Connection.Method.GET).execute();
        Document doc = Jsoup.parse(response.body());
        Element titleEle = doc.getElementById("activity-name");

        //替换名字，因为可能出现该名字不能创建文件夹
        String title = titleEle.text();
        title = title.replaceAll("[/\\\\:*?|]", "_");
        title = title.replaceAll("[\"<>]", "'");
        FileUtils.writeStringToFile(Paths.get(path, title + ".html").toFile(), response.body(), StandardCharsets.UTF_8);
        return title;
    }
}
